"""
B站爬虫使用示例
演示如何使用BilibiliCrawler进行各种爬取任务
"""

from bilibili_crawler import BilibiliCrawler
import json

def example_1_get_user_info():
    """示例1：获取用户基本信息"""
    print("=" * 50)
    print("示例1：获取用户基本信息")
    print("=" * 50)
    
    crawler = BilibiliCrawler()
    
    # 示例UP主UID（可以替换为任何有效的UID）
    uid = "12345678"  # 请替换为真实的UID
    
    user_info = crawler.get_user_info(uid)
    if user_info:
        print(f"用户名: {user_info['name']}")
        print(f"粉丝数: {user_info['follower']:,}")
        print(f"关注数: {user_info['following']:,}")
        print(f"等级: Lv{user_info['level']}")
        print(f"简介: {user_info.get('sign', '暂无简介')}")


def example_2_get_videos_list():
    """示例2：获取用户视频列表"""
    print("\n" + "=" * 50)
    print("示例2：获取用户视频列表")
    print("=" * 50)
    
    crawler = BilibiliCrawler()
    
    uid = "12345678"  # 请替换为真实的UID
    
    # 获取第一页视频
    result = crawler.get_user_videos(uid, page=1, page_size=10)
    if result:
        videos = result['data']['list']['vlist']
        
        print(f"找到 {len(videos)} 个视频:")
        for i, video in enumerate(videos, 1):
            print(f"{i}. {video['title']}")
            print(f"   播放量: {video['play']:,}")
            print(f"   发布时间: {video['created']}")
            print(f"   BV号: {video['bvid']}")
            print()


def example_3_get_video_details():
    """示例3：获取视频详细信息"""
    print("\n" + "=" * 50)
    print("示例3：获取视频详细信息")
    print("=" * 50)
    
    crawler = BilibiliCrawler()
    
    # 示例BV号（可以替换为任何有效的BV号）
    bv_id = "BV1234567890"  # 请替换为真实的BV号
    
    video_info = crawler.get_video_info(bv_id)
    if video_info:
        print(f"标题: {video_info['title']}")
        print(f"简介: {video_info['desc'][:200]}...")
        print(f"UP主: {video_info['owner']['name']}")
        print(f"播放量: {video_info['stat']['view']:,}")
        print(f"点赞数: {video_info['stat']['like']:,}")
        print(f"投币数: {video_info['stat']['coin']:,}")
        print(f"收藏数: {video_info['stat']['favorite']:,}")
        print(f"评论数: {video_info['stat']['reply']:,}")


def example_4_batch_analysis():
    """示例4：批量分析UP主数据"""
    print("\n" + "=" * 50)
    print("示例4：批量分析UP主数据")
    print("=" * 50)
    
    crawler = BilibiliCrawler()
    
    uid = "12345678"  # 请替换为真实的UID
    
    # 爬取前3页视频（避免运行时间过长）
    videos = crawler.crawl_user_all_videos(uid, max_pages=3)
    
    if videos:
        # 生成分析报告
        analysis = crawler.analyze_video_data(videos)
        
        print("📊 数据分析报告:")
        print(f"总视频数: {analysis['total_videos']}")
        print(f"总播放量: {analysis['total_views']:,}")
        print(f"总评论数: {analysis['total_comments']:,}")
        print(f"总点赞数: {analysis['total_likes']:,}")
        print(f"平均播放量: {analysis['avg_views']:,}")
        print(f"平均评论数: {analysis['avg_comments']:,}")
        
        if analysis.get('most_viewed_video'):
            print(f"\n🏆 最高播放量视频:")
            print(f"标题: {analysis['most_viewed_video']['title']}")
            print(f"播放量: {analysis['most_viewed_video']['play']:,}")
        
        if analysis.get('latest_video'):
            print(f"\n🆕 最新视频:")
            print(f"标题: {analysis['latest_video']['title']}")
            print(f"播放量: {analysis['latest_video']['play']:,}")


def example_5_url_extraction():
    """示例5：URL提取功能测试"""
    print("\n" + "=" * 50)
    print("示例5：URL提取功能测试")
    print("=" * 50)
    
    crawler = BilibiliCrawler()
    
    # 测试各种URL格式
    test_urls = [
        "https://space.bilibili.com/12345678",
        "https://space.bilibili.com/12345678/",
        "https://www.bilibili.com/12345678",
        "12345678",
        "https://space.bilibili.com/12345678?from=search"
    ]
    
    print("测试URL提取功能:")
    for url in test_urls:
        uid = crawler.extract_uid_from_url(url)
        print(f"输入: {url}")
        print(f"提取的UID: {uid}")
        print()


def main():
    """运行所有示例"""
    print("🚀 B站爬虫使用示例")
    print("注意：请将示例中的UID和BV号替换为真实值")
    
    # 运行示例（注释掉需要真实数据的示例）
    example_5_url_extraction()  # 这个不需要真实数据，可以直接运行
    
    print("\n⚠️ 其他示例需要真实的UID和BV号才能运行")
    print("请修改代码中的UID和BV号后再运行其他示例")
    
    # 取消注释下面的行来运行其他示例
    # example_1_get_user_info()
    # example_2_get_videos_list()
    # example_3_get_video_details()
    # example_4_batch_analysis()


if __name__ == "__main__":
    main() 